#include "rfid_api.h"
#include "rfid_app.h"
#include "iso14443a.h"
#include "iso14443b.h"
#include "rfid_board.h"
#include "mifare_api.h"
#include "fm1208_app.h"
#include "rfid_protocol.h"
#include "key_conversion.h"
#include "rfid_detection.h"

#if _RFID_FUNCTION_ENABLE_
#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
/**
 * @brief 启动卡检测
 *
 * @param AutoTrueOffAnt - 是否自动关闭天线（true：是 false：否）
 * @return uint16_t      - 当前检测电压
 */
static uint16_t RfidStartCardDetcetion(bool AutoTrueOffAnt);
#endif

/**
 * @brief MIFARE 读卡操作
 *
 * @param CardProtocol         - 卡片协议
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidReadMiFareCardProcess(uint8_t CardProtocol);

/**
 * @brief FM1208 读卡操作
 *
 * @param CardProtocol         - 卡片协议
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidReadCpuCardProcess(uint8_t CardProtocol);

/**
 * @brief 二代身份证读卡操作
 *
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidRead2rdGenerationIdCardProcess(void);

/**
 * @brief 卡检测回调
 *
 * @return bool - 捡卡状态（true：触发 false：静默）
 */
static bool RfidCardDetectionCallback(void);

/**
 * @brief 设备自检回调
 *
 */
static void RfidSelfTestCallback(void);

/**
 * @brief 读卡数据回调
 *
 */
static void RfidReadCardDataCallback(void);

static RfidStatusBit_t RfidStatusBit = {0};

#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
static uint16_t RfidStartCardDetcetion(bool AutoTrueOffAnt)
{
  RfidEnableDetection();
  RfidSetCW(TX1_TX2_CW_ENABLE);
  RfidDelayUs(RFID_WAIT_ANT_STABLE_TIME);

  uint16_t Voltage = RfidGetInputVoltage();

  if (AutoTrueOffAnt == true)
  {
    RfidDisableDetection();
  }

  return Voltage;
}
#endif

static RfidExecuteResult_t RfidReadMiFareCardProcess(uint8_t CardProtocol)
{
  uint8_t i=0;
  RfidExecuteResult_t ExecuteResult = CARD_EVENT_PROCESSING;

  switch (RfidStatusBit.SectorParameter.ExecuteStep)
  {
  case CARD_STEP_START:
  {
    uint8_t CardSerialNumber[RFID_NUMBER_OF_CARD_SERIAL_NUMBER] = {0};

    if (RfidSoftwareReset() == true)
    {
      PRINT("[rfid]: reset rfid chip success.\r\n");

      RfidPcdISOType('A');
      RfidSetCW(TX1_TX2_CW_ENABLE);
      RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

      if (TypeAAuthenticate(CardSerialNumber) == true)
      {
        memcpy(RfidStatusBit.SectorParameter.CardSerialNumber, CardSerialNumber, RFID_NUMBER_OF_MIFARE_CARD_SERIAL_NUMBER);

        if (RfidGetWaitUserActionEn() != true)
        {
          uint8_t SectorKeyValue[RFID_MAX_NUMBER_OF_CODED_TEXT] = {0};

          RfidGetSectorAccessKey(SectorKeyValue);
          RfidStatusBit.SectorParameter.RWSectorId = RfidGetStartSectorNumber();

          CalculatingAccessKeyB(SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueB);
          CalculatingAccessKeyA(CardSerialNumber, SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueA, CardProtocol);
          PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X.\r\n", RfidStatusBit.SectorParameter.KeyValueA[0], RfidStatusBit.SectorParameter.KeyValueA[1],
                RfidStatusBit.SectorParameter.KeyValueA[2], RfidStatusBit.SectorParameter.KeyValueA[3], RfidStatusBit.SectorParameter.KeyValueA[4], RfidStatusBit.SectorParameter.KeyValueA[5]);
//          memset(RfidStatusBit.SectorParameter.KeyValueA,0xFF,sizeof(RfidStatusBit.SectorParameter.KeyValueA));
          if (MifareAuthentication(PICC_AUTHENT1A, RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.KeyValueA, RfidStatusBit.SectorParameter.CardSerialNumber) == true)
          {
            if (MifareBlockRead(RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.SectorDataBuff) == true)
            {
              printf(" read buff \r\n");
              for(i=0;i<(255);i++)
              {
                printf("%02x ",RfidStatusBit.SectorParameter.SectorDataBuff[i]);
              }
              RfidStatusBit.SectorParameter.TotalDatLength = RfidGetRWDataLength(RfidStatusBit.SectorParameter.SectorDataBuff);
              if ((RfidStatusBit.SectorParameter.TotalDatLength > 0) && (RfidStatusBit.SectorParameter.TotalDatLength <= RFID_MAX_LENGTH_OF_OPERATION_DATA))
              {
                RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
                RFidDelayedStartReadCardDataTask(RFID_SECTOR_OPERATION_INTERVAL);
              }
              else
              {
                PRINT("[rfid]: failure to read card, err: CARD_EXECUTE_ERROR, data length: %d.\r\n", RfidStatusBit.SectorParameter.TotalDatLength);
                ExecuteResult = CARD_EXECUTE_ERROR;
              }
            }
            else
            {
              PRINT("[rfid]: failure to read card.\r\n");
              ExecuteResult = CARD_EXECUTE_ERROR;
            }
          }
          else
          {
            PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
            ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
          }
        }
        else
        {
          PRINT("[rfid]: read data complete.\r\n");
          ExecuteResult = CARD_EXECUTE_SUCCESS;
        }
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: CARD_DOES_NOT_EXIST.\r\n");
        ExecuteResult = CARD_DOES_NOT_EXIST;
      }
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_COMMUNICATION_FAILURE.\r\n");
      ExecuteResult = CARD_COMMUNICATION_FAILURE;
    }
  }
  break;

  case CARD_STEP_VERIFY_USER_KEY:
  {
    bool VerifyResult = MifareAuthentication(PICC_AUTHENT1A, RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.KeyValueA, RfidStatusBit.SectorParameter.CardSerialNumber);
    if (VerifyResult == true)
    {
      PRINT("[rfid]: verify user Key successfully.\r\n");

      RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
      RFidDelayedStartReadCardDataTask(RFID_SECTOR_OPERATION_INTERVAL);
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
      ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
    }
  }
  break;

  case CARD_READ_DATA_FROM_SECTOR:
  {
    if (RfidStatusBit.SectorParameter.TotalDatLength > RfidStatusBit.SectorParameter.RWDataSize)
    {
      if (MifareBlockRead((RfidStatusBit.SectorParameter.RWSectorId * 4) + RfidStatusBit.SectorParameter.RWBlockId, &RfidStatusBit.SectorParameter.SectorDataBuff[RfidStatusBit.SectorParameter.RWDataSize]) == true)
      {
        RfidStatusBit.SectorParameter.RWDataSize += MIFARE_CARD_BLOCK_DATA_LENGTH;

        RfidStatusBit.SectorParameter.RWBlockId++;
        if (RfidStatusBit.SectorParameter.RWBlockId >= MIFARE_NUMBER_OF_OPERATION_BLOCK_IN_SECTOR)
        {
          RfidStatusBit.SectorParameter.RWBlockId = 0;

          RfidStatusBit.SectorParameter.RWSectorId++;
          RfidStatusBit.SectorParameter.ExecuteStep = CARD_STEP_VERIFY_USER_KEY;
        }

        RFidDelayedStartReadCardDataTask(RFID_SECTOR_OPERATION_INTERVAL);
      }
      else
      {
        PRINT("[rfid]: failure to read card.\r\n");
        ExecuteResult = CARD_EXECUTE_ERROR;
      }
    }
    else
    {
      ExecuteResult = CARD_EXECUTE_SUCCESS;

      PRINT("[rfid]: read data complete, length :%d, data: ", RfidStatusBit.SectorParameter.RWDataSize);
      for (uint16_t i = 0; i < RfidStatusBit.SectorParameter.RWDataSize; i++)
        PRINT("%02X", RfidStatusBit.SectorParameter.SectorDataBuff[i]);
      PRINT(".\r\n");
    }
  }
  break;

  default:
  {
    PRINT("[rfid]: failure to read card, err: code run failure.\r\n");
    ExecuteResult = CARD_EXECUTE_ERROR;
  }
  break;
  }

  return ExecuteResult;
}

static RfidExecuteResult_t RfidReadCpuCardProcess(uint8_t CardProtocol)
{
  RfidExecuteResult_t ExecuteResult = CARD_EVENT_PROCESSING;

  switch (RfidStatusBit.SectorParameter.ExecuteStep)
  {
  case CARD_STEP_START:
  {
    if (RfidSoftwareReset() == true)
    {
      PRINT("[rfid]: reset rfid chip success.\r\n");

      RfidPcdISOType('A');
      RfidSetCW(TX1_TX2_CW_ENABLE);
      RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

      if (TypeAAuthenticate(RfidStatusBit.SectorParameter.CardSerialNumber) == true)
      {
        RfidStatusBit.SectorParameter.ExecuteStep = CARD_STEP_VERIFY_USER_KEY;
        RfidStartReadCardDataTaskNoWait();
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: CARD_DOES_NOT_EXIST.\r\n");
        ExecuteResult = CARD_DOES_NOT_EXIST;
      }
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_COMMUNICATION_FAILURE.\r\n");
      ExecuteResult = CARD_COMMUNICATION_FAILURE;
    }
  }
  break;

  case CARD_STEP_VERIFY_USER_KEY:
  {
    bool VerifySuccessEn = false;

    if (FmcosRats() == true)
    {
      char *pDirectorName = NULL;

      if (FmcosSelectCardDirector(CPU_CARD_MAIN_DIRECTORY) == true)
      {
        switch (CardProtocol)
        {
        case RFID_CARD_PROTOCOL_HZ:
          pDirectorName = HZ_CPU_USER_DIRECTOR_NAME;
          break;

        default:
          pDirectorName = YG_CPU_USER_DIRECTOR_NAME;
          break;
        }

        if (FmcosEnterDirectoryByFileName(pDirectorName) == true)
        {
          uint8_t Random[8] = {0};

          if (FmcosGetRandomData(4, Random) == true)
          {
            uint8_t EncryptedText[8] = {0}, VerificationKey[8] = {0}, SectorKeyValue[RFID_MAX_NUMBER_OF_CODED_TEXT] = {0};

            memset(EncryptedText, 0, 8);
            memcpy(EncryptedText, Random, 8);

//            RfidGetSectorAccessKey(SectorKeyValue); //读取杨格卡秘钥
//            CalculatingAccessKeyA(RfidStatusBit.SectorParameter.CardSerialNumber, SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueA, CardProtocol);//对秘钥加密，从而进行下一步获取加密随机数
            RfidCalDesEncrypt(RfidStatusBit.SectorParameter.KeyValueA, EncryptedText, VerificationKey);
            PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X%02X%02X.\r\n", VerificationKey[0], VerificationKey[1], VerificationKey[2],
                  VerificationKey[3], VerificationKey[4], VerificationKey[5], VerificationKey[6], VerificationKey[7]);

            if (FmcosExternalVerification(VerificationKey, 8) == true)
            {
              if (FmcosSelectCardDirector(CPU_BINARY_FILE_DIRECTORY) == true)
              {
                uint16_t ReturnDataSize = 0;
                uint8_t ReturnDataBuff[FM1208_OPERATION_DATA_SIZE] = {0};

                if (FmcosReadBinFile(0, RfidStatusBit.SectorParameter.SectorDataBuff, &ReturnDataSize) == true)
                {
                  RfidStatusBit.SectorParameter.TotalDatLength = RfidGetRWDataLength(RfidStatusBit.SectorParameter.SectorDataBuff);
                  if ((RfidStatusBit.SectorParameter.TotalDatLength > 0) && (RfidStatusBit.SectorParameter.TotalDatLength <= RFID_MAX_LENGTH_OF_OPERATION_DATA))
                  {
                    VerifySuccessEn = true;
                  }
                }
              }
            }
          }
        }
      }
    }

    if (VerifySuccessEn == true)
    {
      PRINT("[rfid]: verify user Key successfully.\r\n");

      RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
      RfidStartReadCardDataTaskNoWait();
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
      ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
    }
  }
  break;

  case CARD_READ_DATA_FROM_SECTOR:
  {
    uint16_t ReturnDataSize = 0;
    uint8_t ReturnDataBuff[FM1208_OPERATION_DATA_SIZE] = {0};

    if (RfidStatusBit.SectorParameter.TotalDatLength > RfidStatusBit.SectorParameter.RWDataSize)
    {
      if (FmcosReadBinFile(RfidStatusBit.SectorParameter.RWDataSize, ReturnDataBuff, &ReturnDataSize) == true)
      {
        uint16_t CopyDataSize = RfidStatusBit.SectorParameter.TotalDatLength - RfidStatusBit.SectorParameter.RWDataSize;
        if (CopyDataSize > FM1208_READ_WRITE_DATA_SIZE)
        {
          CopyDataSize = FM1208_READ_WRITE_DATA_SIZE;
        }

        memcpy(&RfidStatusBit.SectorParameter.SectorDataBuff[RfidStatusBit.SectorParameter.RWDataSize], ReturnDataBuff, CopyDataSize);
        RfidStatusBit.SectorParameter.RWDataSize += CopyDataSize;

        RfidStartReadCardDataTaskNoWait();
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: access sector failure.\r\n");
        ExecuteResult = CARD_EXECUTE_ERROR;
      }
    }
    else
    {
      PRINT("[rfid]: read data complete.\r\n");
      ExecuteResult = CARD_EXECUTE_SUCCESS;
    }
  }
  break;

  default:
  {
    PRINT("[rfid]: failure to read card, err: code run failure.\r\n");
    ExecuteResult = CARD_EXECUTE_ERROR;
  }
  break;
  }

  return ExecuteResult;
}

static RfidExecuteResult_t RfidRead2rdGenerationIdCardProcess(void)
{
  uint8_t ReadCardNumber[64] = {0}, SnrLength = 0;
  RfidExecuteResult_t ExecuteResult = CARD_DOES_NOT_EXIST;

  RfidSoftwareReset();
  RfidPcdISOType('B');
  RfidSetCW(TX1_TX2_CW_ENABLE);
  RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

  for (uint8_t i = 0; i < 5; i++)
  {
    if (TypeBRequest(ReadCardNumber) == true)
    {
      if (TypeBSelect(ReadCardNumber) == true)
      {
        if (TypeBGetUID(ReadCardNumber, &SnrLength) == true)
        {
          if (SnrLength <= RFID_NUMBER_OF_CARD_SERIAL_NUMBER)
          {
            ExecuteResult = CARD_EXECUTE_SUCCESS;
            memcpy(RfidStatusBit.SectorParameter.CardSerialNumber, ReadCardNumber, RFID_NUMBER_OF_CARD_SERIAL_NUMBER);
          }
        }
      }
    }
  }

  return ExecuteResult;
}

static bool RfidCardDetectionCallback(void)
{
#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
  uint16_t Voltage = RfidStartCardDetcetion(true);
  // PRINT("%d\r\n", Voltage);

  uint16_t Sensitivity = (RfidGetDeviceActiveStatus() == true) ? RfidStatusBit.SystemParameter.ActiveAntennaVoltage : RfidStatusBit.SystemParameter.DefaultAntennaVoltage;
  if (Voltage < Sensitivity)
  {
    if (RfidStatusBit.SystemParameter.WaitCardRelease != true)
    {
      PRINT("[rfid]: there's a card approaching.\r\n");

      if (RfidReportedCardNearby() == true)
      {
        RfidStatusBit.SystemParameter.WaitCardRelease = true;
        memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));

        RfidCardDetectionConfiguration(false);
        return true;
      }
      else
      {
        PRINT("[rfid]: report failure.\r\n");
      }
    }
  }
  else
  {
    if (RfidStatusBit.SystemParameter.WaitCardRelease == true)
    {
      PRINT("[rfid]: card removed.\r\n");
      RfidStatusBit.SystemParameter.WaitCardRelease = false;
    }
  }

#else
  RfidExitCardDetectionMode();

  PRINT("[rfid]: there's a card approaching.\r\n");

  if (RfidGetDeviceBusyEn() != true)
  {
    if (RfidReportedCardNearby() == true)
    {
      memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
      return true;
    }
  }
  else
  {
    memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
    RfidStartReadCardDataTaskNoWait();
    return true;
  }

  RfidEnterCardDetectionMode();
#endif

  return false;
}

static void RfidSelfTestCallback(void)
{
#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
  switch (RfidStatusBit.SelfTestStep)
  {
  case RFID_GET_ATCIVE_ANTENNA_VOLTAGE:
  {
    uint16_t Voltage = RfidStartCardDetcetion(true);
    PRINT("[rfid]: detcetion voltage: %d.\r\n", Voltage);

    RfidStatusBit.SystemParameter.AntennaVoltage[RfidStatusBit.SystemParameter.ValidTimes++] = Voltage;
    if (RfidStatusBit.SystemParameter.ValidTimes >= RFID_ANTENNA_CALIBRATION_COUNT)
    {
      {
        uint32_t TotalAntennaVoltage = 0;
        for (uint8_t i = 0; i < RFID_ANTENNA_CALIBRATION_COUNT; i++)
        {
          TotalAntennaVoltage += RfidStatusBit.SystemParameter.AntennaVoltage[i];
        }

        RfidStatusBit.SystemParameter.ActiveAntennaVoltage = (uint16_t)(TotalAntennaVoltage / RFID_ANTENNA_CALIBRATION_COUNT);
        if (RfidStatusBit.SystemParameter.ActiveAntennaVoltage >= RFID_CARD_NEAR_ATTENUATION_VOLTAGE)
        {
          RfidStatusBit.SystemParameter.ActiveAntennaVoltage -= RFID_CARD_NEAR_ATTENUATION_VOLTAGE;
        }
      }

      {
        RfidPlayExitSelfTestSound();
        RfidStatusBit.SystemParameter.ValidTimes = 0;
        RfidStatusBit.SelfTestStep = RFID_GET_DEFAULT_ANTENNA_VOLTAGE;
      }
    }

    RFidDelayedStartSelfTestTask(RFID_GET_ANT_VOLT_INTERVAL);
  }
  break;

  case RFID_GET_DEFAULT_ANTENNA_VOLTAGE:
  {
    uint16_t Voltage = RfidStartCardDetcetion(true);
    PRINT("[rfid]: detcetion voltage: %d.\r\n", Voltage);

    RfidStatusBit.SystemParameter.AntennaVoltage[RfidStatusBit.SystemParameter.ValidTimes++] = Voltage;
    if (RfidStatusBit.SystemParameter.ValidTimes == RFID_ANTENNA_CALIBRATION_COUNT)
    {
      {
        uint32_t TotalAntennaVoltage = 0;
        for (uint8_t i = 0; i < RFID_ANTENNA_CALIBRATION_COUNT; i++)
        {
          TotalAntennaVoltage += RfidStatusBit.SystemParameter.AntennaVoltage[i];
        }

        RfidStatusBit.SystemParameter.DefaultAntennaVoltage = (uint16_t)(TotalAntennaVoltage / RFID_ANTENNA_CALIBRATION_COUNT);
        if (RfidStatusBit.SystemParameter.DefaultAntennaVoltage >= RFID_CARD_NEAR_ATTENUATION_VOLTAGE)
        {
          RfidStatusBit.SystemParameter.DefaultAntennaVoltage -= RFID_CARD_NEAR_ATTENUATION_VOLTAGE;
        }
      }

      {
        RfidDisableDetection();
        RfidStatusBit.SystemParameter.ValidTimes = 0;
        RfidStatusBit.SelfTestStep = RFID_SELF_TEST_IDLE;

        PRINT("[rfid]: default antenna voltage: %d, active antenna voltage: %d.\r\n", RfidStatusBit.SystemParameter.DefaultAntennaVoltage, RfidStatusBit.SystemParameter.ActiveAntennaVoltage);
        bool SelfTestResult = ((RfidStatusBit.SystemParameter.DefaultAntennaVoltage >= RFID_MIX_READ_CARD_SENSITIVITY) && (RfidStatusBit.SystemParameter.ActiveAntennaVoltage >= RFID_MIX_READ_CARD_SENSITIVITY)) ? true : false;
        RfidReportSelfTestResult(SelfTestResult);
      }
    }
    else
    {
      RFidDelayedStartSelfTestTask(RFID_GET_ANT_VOLT_INTERVAL);
    }
  }
  break;

  default:
  {
    RfidEnableDetection();

    if (RfidSoftwareReset() != true)
    {
      RfidReportSelfTestResult(false);
    }
    else
    {
      RfidStatusBit.SystemParameter.ValidTimes = 0;
      RfidStatusBit.SystemParameter.ActiveAntennaVoltage = 0;
      RfidStatusBit.SystemParameter.DefaultAntennaVoltage = 0;
      RfidStatusBit.SelfTestStep = RFID_GET_ATCIVE_ANTENNA_VOLTAGE;

      RfidPlayStartSelfTestSound();
      RfidStartSelfTestTaskNoWait();
    }
  }
  break;
  }

#else
  bool SelfTestResult = RfidSoftwareReset();
  RfidReportSelfTestResult(SelfTestResult);
//  RfidSetCW(TX1_TX2_CW_ENABLE);  //打开一直检卡
#endif
}

static void RfidReadCardDataCallback(void)
{
  RfidReadCard_t ReadCardType = RfidGetReaderCardType();
  RfidExecuteResult_t ExecuteResult = CARD_NOT_SUPPORTED;
  uint8_t CardProtocol = (uint8_t)RfidGetCardReadingProtocol();

#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
  uint16_t Voltage = RfidStartCardDetcetion(false);

  uint16_t Sensitivity = (RfidGetDeviceActiveStatus() == true) ? RfidStatusBit.SystemParameter.ActiveAntennaVoltage : RfidStatusBit.SystemParameter.DefaultAntennaVoltage;
  if (Voltage < Sensitivity)
  {
    if (RfidStatusBit.SystemParameter.ValidTimes < RFID_REPEAT_READ_CARD_TIMES)
    {
      RfidStatusBit.SystemParameter.ValidTimes++;

      RfidDisableDetection();
      RFidDelayedStartReadCardDataTask(RFID_REPEAT_READ_CARD_INTERVAL);

      return;
    }
  }
  else
  {
    RfidStatusBit.SystemParameter.ValidTimes = 0;
    RfidStatusBit.SystemParameter.WaitCardRelease = false;

    RfidDisableDetection();
    RfidEnableCardDecetionFunction();

    return;
  }
#endif

  {
    switch (ReadCardType)
    {
    case MIFARE_CARD_MODE:
      ExecuteResult = RfidReadMiFareCardProcess(CardProtocol);
      break;

    case STANDBY_CPU_MODE:
      ExecuteResult = RfidReadCpuCardProcess(CardProtocol);
      break;

    case _2RD_GENERATION_ID_CARD:
      ExecuteResult = RfidRead2rdGenerationIdCardProcess();
      break;
    }

    if (ExecuteResult != CARD_EVENT_PROCESSING)
    {
      RfidStatusBit.SystemParameter.ValidTimes = 0;

      if (ExecuteResult != CARD_DOES_NOT_EXIST)
      {
        if (RfidGetWaitUserActionEn() == true)
        {
          RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
        }
        else
        {
          if (RfidValidateCardDataValidity(RfidStatusBit.SectorParameter.SectorDataBuff, RfidStatusBit.SectorParameter.CardSerialNumber, CardProtocol) != true)
          {
            RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
          }
          else
          {
            RfidReportedCardSerialNumber(NULL);
          }
        }
      }
      else
      {
        RfidStatusBit.SystemParameter.WaitCardRelease = false;
        (RfidGetWaitUserActionEn() == true) ? RfidEnableCardDecetionFunction() : RfidReportedCardSerialNumber(NULL);
      }
    }
    else
    {
      RFidDelayedStartReadCardDataTask(RFID_READ_CARD_DATA_INTERVAL);
    }
  }
}
#endif

void RfidEnableCardDecetionFunction(void)
{
#if _RFID_FUNCTION_ENABLE_

#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
  RfidCardDetectionConfiguration(true);

#else
  RfidEnterCardDetectionMode();
#endif

#endif
}

void RfidDisableCardDecetionFunction(void)
{
#if _RFID_FUNCTION_ENABLE_

#if _CARD_DETECTION_TYPE_ == _CARD_DETECTION_ADC_
  RfidDisableDetection();
  RfidCardDetectionConfiguration(false);

#else
  RfidExitCardDetectionMode();
#endif

#endif
}

bool RfidStartDeviceSelfTestTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStatusBit.SelfTestStep = RFID_CONNECTION_TEST;
  RfidStartSelfTestTaskNoWait();
  return true;

#else
  return false;
#endif
}

bool RfidStartReadCardDataTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStartReadCardDataTaskNoWait();
  return true;

#else
  return false;
#endif
}

bool RfidStartLocalRegisterUserTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  if (RfidStatusBit.SystemParameter.BusyEn != true)
  {
    RfidStatusBit.SystemParameter.BusyEn = true;
    memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));

    RfidPreparationsBeforeLocalRegister();
    return true;
  }
#endif

  return false;
}

void RfidExitCurrectTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStatusBit.SystemParameter.BusyEn = false;
  memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
#endif
}

void RfidConfiguration(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidExternFunctionTable_t ExternFunctionTable = {0};

  ExternFunctionTable.SelfTestTask = RfidSelfTestCallback;
  ExternFunctionTable.ReadCardDataTask = RfidReadCardDataCallback;
  ExternFunctionTable.CardDetectionTask = RfidCardDetectionCallback;
  RfidBoardInitialisation(&ExternFunctionTable);

  memset(&RfidStatusBit, 0, sizeof(RfidStatusBit_t));
#endif
}
